package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisIdService redisIdService;

    @Autowired
    private MovementAsyncService movementAsyncService;

    @Override
    public void saveMovement(Movement movement) {
        // 0.redis主键自增
        Long pid = redisIdService.getNextId(ConstantUtil.MOVEMENT_ID);
        movement.setPid(pid);
        // 1.保存动态详情
        mongoTemplate.save(movement);
        // 2.调用新线程保存好友动态（异步）
        movementAsyncService.saveMovementFriend(movement);
    }

    // 查询我的动态
    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建查询条件
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query(  // 条件
                Criteria.where("userId").is(userId)
                        .and("state").is(1)
        ).with(Sort.by(Sort.Order.desc("created"))) // 排序
                .skip(index).limit(pageSize); // 分页
        // 2.查询动态详情
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        // 3.查询总记录数
        long counts = mongoTemplate.count(query, Movement.class);
        // 4.返回并封装分页对象
        return new PageBeanVo(pageNum, pageSize, counts, movementList);
    }

    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建条件
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created"))) // 排序
                .skip(index).limit(pageSize); // 分页
        // 2.查询好友动态表
        List<FriendMovement> friendMovementList = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        // 3.遍历好友动态
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(friendMovementList)) {
            for (FriendMovement friendMovement : friendMovementList) {
                // 根据动态id查询动态详情
                ObjectId publishId = friendMovement.getPublishId();
                Movement movement = mongoTemplate.findById(publishId, Movement.class);
                // 判断动态状态
                if (movement.getState() == 1) {
                    // 设置到集合中
                    movementList.add(movement);
                }
            }
        }
        // 4.返回并封装pageBeanVo
        return new PageBeanVo(pageNum, pageSize, 0L, movementList);
    }

    // 查询推荐动态
    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        // 1.构建条件
        Integer index = (pageNum - 1) * pageSize;
        Query query = new Query(
                Criteria.where("userId").is(userId) // 条件
        ).with(Sort.by(Sort.Order.desc("created")))
                .with(Sort.by(Sort.Order.desc("score"))) // 排序
                .skip(index).limit(pageSize); // 分页
        // 2.查询推荐动态列表
        List<RecommendMovement> recommendMovementList = mongoTemplate.find(query, RecommendMovement.class);
        // 3.遍历
        List<Movement> movementList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendMovementList)) {
            for (RecommendMovement recommendMovement : recommendMovementList) {
                // 根据推荐动态id查询动态详情
                ObjectId publishId = recommendMovement.getPublishId();
                Movement movement = mongoTemplate.findById(publishId, Movement.class);

                if (movement.getState() == 1) {
                    // 添加到集合
                    movementList.add(movement);
                }

            }
        }
        // 4.返回并封装pageBeanVo
        return new PageBeanVo(pageNum, pageSize, 0L, movementList);
    }

    @Override
    public Movement findById(ObjectId id) {
        return mongoTemplate.findById(id, Movement.class);
    }

    // 后台查询动态列表
    @Override
    public PageBeanVo findMovementByPage(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        // 1.构建条件
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum-1)*pageSize).limit(pageSize);
        // 动态条件
        if (userId!=null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state!=null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        // 2.查询list
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        // 3.查询总记录数
        Query queryCount = new Query();
        if (userId!=null) {
            queryCount.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state!=null) {
            queryCount.addCriteria(Criteria.where("state").is(state));
        }
        long counts = mongoTemplate.count(queryCount, Movement.class);
        // 4.返回并封装分页对象
        return new PageBeanVo(pageNum, pageSize, counts, movementList);
    }

    @Override
    public void update(Movement movement) {
        mongoTemplate.save(movement);
    }
}
